import {
  createSlice,
  PayloadAction,
  createAsyncThunk,
  ActionReducerMapBuilder
} from "@reduxjs/toolkit"
import axios from "axios"
import { checkout } from "../shoppingCart/slice"

interface OrderState {
  loading: boolean
  error: string | null
  currentOrder: any
  // data:{
  //   id:''
  //   userId:''
  //   orderItems:[] //同购物车信息
  //   state:'' //pending 等待支付状态、completed支付完成 
  // }
}

const initialState: OrderState = {
  loading: true,
  error: null,
  currentOrder: null
}

export const placeOrder = createAsyncThunk(
  "order/placeOrder",
  async (parameters: { jwt: string; orderId: string }, thunkAPI) => {
    const { data } = await axios.post(
      `http://123.56.149.216:8080/api/orders/${parameters.orderId}/placeOrder`,
      null,
      {
        headers: {
          Authorization: `bearer ${parameters.jwt}`
        }
      }
    )
    return data
  }
)

export const orderSlice = createSlice({
  name: "order",
  initialState,
  reducers: {},
  extraReducers: (builder: ActionReducerMapBuilder<OrderState>) => {
    builder
      .addCase(placeOrder.pending, (state) => {
        // 处理pending状态，比如设置加载标志
        // return { ...state, loading: true };
        state.loading = true
      })
      .addCase(placeOrder.fulfilled, (state, action) => {
        // 处理fulfilled状态，使用action.payload更新state
        state.currentOrder = action.payload
        state.loading = false
        state.error = null
      })
      .addCase(placeOrder.rejected, (state, action) => {
        // 处理rejected状态，比如设置错误信息
        //   const ddd = action.payload;
        state.loading = false
        // state.error = action.payload
      })
      .addCase(checkout.pending, (state) => {
        // 处理pending状态，比如设置加载标志
        // return { ...state, loading: true };
        state.loading = true
      })
      .addCase(checkout.fulfilled, (state, action) => {
        // 处理fulfilled状态，使用action.payload更新state
        state.currentOrder = action.payload
        state.loading = false
        state.error = null
      })
      .addCase(checkout.rejected, (state, action) => {
        // 处理rejected状态，比如设置错误信息
        //   const ddd = action.payload;
        state.loading = false
        // state.error = action.payload
      })
  }
})
